package com.gitee.hermer.engine.jars.demo.core.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.atomikos.icatch.CompositeCoordinator;
import com.atomikos.icatch.CompositeTransaction;
import com.atomikos.icatch.config.Configuration;
import com.atomikos.icatch.provider.ConfigProperties;
import com.atomikos.recovery.TxState;
import com.gitee.hermer.boot.jee.commons.exception.ErrorCode;
import com.gitee.hermer.boot.jee.commons.exception.PaiUException;
import com.gitee.hermer.engine.jars.demo.core.po.TestPOExample;
import com.gitee.hermer.engine.jars.demo.core.service.ITestService;

@Service
public class TestServiceImpl {
	
	@Autowired
	private ITestService service;
	
	@Autowired
	private TestServiceImpl2 impl2;
	
//	@Autowired
//	private IdGenerateRule generateRule;
	

	
	@Transactional
	public String updateTestPO(){
//		TestPOExample example = new TestPOExample();
//		example.createCriteria().andCreateOwnerEqualTo("admin");
//		dao.selectByExample(example);
		String key = service.updateTestPO();
//		generateRule.generateId();
		throw new RuntimeException(key);
	}
	
	@Scheduled(fixedDelay=5000)
	public void test22(){
		List<Future> futureList= new ArrayList<>();
		for (int i = 0;i< 2;i++) {
			ExecutorService executor = Executors.newCachedThreadPool();
			Future<String> future =executor.submit(()->{
				impl2.updateTestPO();
				return "end";
			});
			futureList.add(future);
		}
		
		for (Future future : futureList) {
			try {
				future.get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}


	}
	
	
	/**
	 * 模拟超时回滚
	 * @return
	 * @throws InterruptedException 
	 */
	@Transactional
	public String updateTestPO2(List<String> res) throws InterruptedException{
//		TestPOExample example = new TestPOExample();
//		example.createCriteria().andCreateOwnerEqualTo("admin");
//		dao.selectByExample(example);
		res.add(service.updateTestPO());
		//wasSetToRollbackOnly  CoordinatorImp
		int i = 0;
		while (i < 10) {
			i += 1;
			Thread.currentThread();
			Thread.sleep(1000l);
		}
		return res.get(0);
	}
}
